#!/bin/bash
# Performs basic checks for tools required by Magic Modules.
# This must be in bash because no other tools are guaranteed to be present.

set -e
exitcode=0

if [ -t 1 ]; then
    red=$'\e[1;31m'
    grn=$'\e[1;32m'
    yel=$'\e[1;33m'
    blu=$'\e[1;34m'
    mag=$'\e[1;35m'
    cyn=$'\e[1;36m'
    end=$'\e[0m'
else
    red=''
    grn=''
    yel=''
    blu=''
    mag=''
    cyn=''
    end=''
fi

warn() {
    printf "%s\n" "${!1}${2}${end}"
}

found=0
count_in_path() {
    echo "Check for ${1} in path..."
    found=$(which -a "${1}" | uniq | wc -l)
}

count_in_path "go"
if [ $found -eq 0 ]; then
    exitcode=1
    warn "yel" "   go not found. See https://golang.org/doc/install for information on installing it."
else
    version=($(go version))
    version=${version[2]}
    if [[ "$version" < "go1.24.0" ]]; then
        exitcode=1
        warn "yel" "   $version is installed, but go 1.24 or later is required. See https://golang.org/doc/install for information on installing it."
    fi
    if [[ -z "${GOPATH}" ]]; then
        exitcode=1
        warn "yel" "   GOPATH is not set. Add 'export GOPATH=\$HOME/go' to your terminal's startup script and restart your terminal."
    fi
    if [ $exitcode -eq 0 ]; then
        warn "grn" "   found!"
    fi
fi

count_in_path "git"
if [ $found -eq 0 ]; then
    exitcode=1
    warn "yel" "   git not found. See https://git-scm.com/book/en/v2/Getting-Started-Installing-Git"
    warn "yel" "   for information on installing it."
else
    warn "grn" "   found!"
fi

count_in_path "terraform"
if [ $found -eq 0 ]; then
    exitcode=1
    warn "yel" "   terraform not found. See https://learn.hashicorp.com/tutorials/terraform/install-cli"
    warn "yel" "   for information on installing it. Version 1.1.8 or later recommended."
else
    warn "grn" "   found!"
fi


count_in_path "make"
if [ $found -eq 0 ]; then
    exitcode=1
    warn "yel" "   make not found. See https://www.gnu.org/software/make/ for information on downloading it."
else
    warn "grn" "   found!"
fi

exit $exitcode
